home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 14540 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.3 KB

  1. Path: solon.com!not-for-mail
  2. From: loreti@mxsld2.pd.infn.it (Maurizio Loreti)
  3. Newsgroups: comp.lang.c.moderated,comp.lang.c
  4. Subject: Re: fflush(stdin) - not guaranteed to work?
  5. Date: 15 Apr 1996 13:09:37 -0500
  6. Organization: I.N.F.N. Padova - CDF/CMS VAXcluster
  7. Sender: clc@solutions.solon.com
  8. Approved: clc@solutions.solon.com
  9. Message-ID: <4ku3d1$50s@solutions.solon.com>
  10. References: <4ksjpn$rjt@solutions.solon.com>
  11. Reply-To: loreti@mxsld2.pd.infn.it
  12. NNTP-Posting-Host: solutions.solon.com
  13.  
  14. In article <4ksjpn$rjt@solutions.solon.com>, gohel@csee.usf.edu (Himanshu Gohel) writes:
  15. >In Paul S. Wang's "Introduction to ANSI C on UNIX" he says that
  16. >the fflush() function was "not intended to control input buffering"
  17. >on page 266.
  18. >
  19. >My question is, why?  Some of my students have written programs using
  20. >fflush(stdin) hoping it would clear away anything that's in the input
  21. >buffer before a scanf() statement and apparently it works on some PC
  22. >based compilers, but when re-compiled on a UNIX system, it does not
  23. >always work.
  24.  
  25. Apparently you missed Q/A 12.26 of the FAQ list,
  26. RTFM.mit.edu:pub/usenet/comp.lang.c/*:
  27.  
  28. 12.26:    How can I flush pending input so that a user's typeahead isn't
  29.     read at the next prompt?  Will fflush(stdin) work?
  30.  
  31. A:    fflush() is defined only for output streams.  Since its
  32.     definition of "flush" is to complete the writing of buffered
  33.     characters (not to discard them), discarding unread input would
  34.     not be an analogous meaning for fflush on input streams.
  35.  
  36.     There is no standard way to discard unread characters from a
  37.     stdio input stream, nor would such a way be sufficient unread
  38.     characters can also accumulate in other, OS-level input buffers.
  39.  
  40.     References: ANSI Sec. 4.9.5.2; ISO Sec. 7.9.5.2; H&S Sec. 15.2.
  41.  
  42. >What is the best way to get rid of the '\n' from the input buffer after
  43. >a scanf() statement?  In the same book on page 263 I've seen the following
  44. >format used in an fscanf() format specifier:
  45. >
  46. > %*[\n]
  47.  
  48. The best way is to not use scanf at all :-)
  49.  
  50. Try fgets to read a whole line, if you want destroy the '\n' (if any!)
  51. with an appropriate statement (the FAQ list in Q/A 7.1 suggests
  52.   if((p = strchr(answer, '\n')) != NULL) *p = '\0';
  53. ), then parse appropriately the input line.
  54. --
  55. Maurizio Loreti                       http://mvxpd5.pd.infn.it/wwwcdf/mlo.html
  56. Un. of Padova, Dept. of Physics - Padova, Italy          loreti@padova.infn.it
  57.